package com.atguigu.yygh.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.Date;

public class JwtHelper {
    private static long tokenExpiration = 24 * 60 * 60 * 1000;
    private static String secretString = "atguigu123456";

    /**
     * 生成JWT
     *
     * @param userId   用户ID
     * @param userName 用户名
     * @return 得到令牌
     */
    public static String createToken(Long userId, String userName) {

        String token = Jwts.builder()
                //1、设置JWT头（可省略）
                .setHeaderParam("alg", "HS256")
                .setHeaderParam("typ", "JWT")
                //2、公共数据
                .setSubject("YYGH-USER") //主题
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)) //过期时间
                //3、私有数据
                .claim("userId", userId) //用户ID
                .claim("userName", userName) //用户名
                //4、签名hash   secretString : 秘钥
                .signWith(SignatureAlgorithm.HS256, secretString.getBytes(StandardCharsets.UTF_8)) //签名
                //5、生成token
                .compact();

        return token;
    }

    /**
     * 解析JWT
     *
     * @param token
     * @return 得到JWT载荷(令牌中存储的数据)
     */
    public static Claims parseToken(String token) {
        Jws<Claims> claimsJws =
                Jwts.parser().setSigningKey(secretString.getBytes(StandardCharsets.UTF_8)).parseClaimsJws(token);
                //返回载荷信息
        return claimsJws.getBody();
    }

    //通过token获取UserId
    public static Long getUserId(String token) {
        if(StringUtils.isEmpty(token)) return null;
        Claims claims = parseToken(token);
        Integer id = (Integer)claims.get("userId");
        return id.longValue();
    }

    //通过token获取UserName
    public static String getUserName(String token) {
        if(StringUtils.isEmpty(token)) return "";
        Claims claims = parseToken(token);
        String name = (String)claims.get("userName");
        return name;
    }

    public static void main(String[] args) {
        String token = JwtHelper.createToken(1L, "helen");
        System.out.println(token);

        System.out.println(JwtHelper.getUserId(token));
        System.out.println(JwtHelper.getUserName(token));
    }
}
